import json
import os
from typing import List
#123
class usersystem():
    def __init__(self):
        self.users = {}
        # 一个字典，user-password键值对,两者都是字符串类型
        self.users_wrongans = {}
        # 存放错题，一个字典嵌套的字典，类似于{"zhouxinyi":{"2019.10.8":["2+3="],1:["1+1="]}}
        self.users_wrongans_del = {}
        # 存放错题，单独的一个字典
        self.answersys = {}
        self.current_user = "" # 当前登录的user
        self.savefolder = './data/'
        self.filename1 = self.savefolder + "users.json"
        self.filename2 = self.savefolder + "user_wrong.json"
        self.filename3 = self.savefolder + "user_wrong1.json"
        self.filename4 = self.savefolder + "user_ans.json"

    # 每次调用的时候都初始化一次避免出现错误，一定要初始化一次！！！！！！！！然后调用已经存储过的两个json文件
    def initialization(self):
        self.users = {}
        self.users_wrongans = {}
        self.users_wrongans_del = {}
        self.answersys = {}
        self.current_user = ""
        if not os.path.exists(self.savefolder):
            os.mkdir(self.savefolder)
        if not os.path.exists(self.filename1):      # 这里如果用_exists的话，会覆盖原先文件，造成BUG
            self.writefile_user()
        if not os.path.exists(self.filename2):
            self.writefile_wrongans()
        if not os.path.exists(self.filename3):
            self.writefile_wrongans1()
        if not os.path.exists(self.filename4):
            self.writefile_anssys()
        # self.loadfile_user()
        # self.loadfile_wrongans()
        # self.loadfile_wrongans2()

    def userlogin(self, user_pass: tuple) -> int:  # user_pass是个二元组，返回值-1，0，1分别代表没有该用户（应该创建），密码错误和成功登录,你可以输出错误信息
        (user, password) = user_pass
        if user not in self.users.keys():
            return -1
        else:
            if password == self.users[user]:
                self.current_user = user
                return 1
            else:
                return 0

    def accountcreate(self, user_pass_ans: tuple) -> int:  # 返回值0或者1，0代表当前用户已经存在，1代表创建成功
        (user, password, ans) = user_pass_ans
        if user in self.users.keys():
            return 0
        else:
            self.users[user] = password
            self.answersys[user] = (password,ans)
            return 1

    def password_adj(self, user_pass: tuple, new_pass: str) -> int:  # -1代表无用户，0代表原密码错误，1代表修改成功
        (user, password) = user_pass
        if user not in self.users.keys():
            return -1
        else:
            if not password == self.users[user]:
                return 0
            else:
                self.users[user] = new_pass
                return 1

    def loadfile_user(self):  # 用于打开文件,读取已经保存过的user的信息,该filename应该为json格式
        with open(self.filename1, 'r') as file_object:
            diction = json.load(file_object)
        self.users.update(diction)

    def loadfile_wrongans(self):  # 用于打开文件读取错题信息，为json格式
        with open(self.filename2, 'r') as file_object:
            diction = json.load(file_object)
        self.users_wrongans.update(diction)

    def loadfile_wrongans2(self):  # 打开文件读取错题信息2
        with open(self.filename3, 'r') as file_object:
            diction = json.load(file_object)
        self.users_wrongans_del.update(diction)

    def loadfile_anssys(self):  #用于读取用户找回密码的文件
        with open(self.filename4,'r') as file_object:
            diction = json.load(file_object)
        self.answersys.update(diction)

    def writefile_user(self):  # 将当下的字典再次存入filename1中，注意调用的时间，否则会造成文件损坏
        json_str = json.dumps(self.users, indent=4)
        with open(self.filename1, 'w') as file_object:
            file_object.write(json_str)

    def writefile_wrongans(self):  # 将字符串字典存入filename2中
        json_str = json.dumps(self.users_wrongans, indent=4)
        with open(self.filename2, 'w') as file_object:
            file_object.write(json_str)

    def writefile_wrongans1(self):
        json_str = json.dumps(self.users_wrongans_del, indent=4)
        with open(self.filename3, 'w') as file_object:
            file_object.write(json_str)

    def writefile_anssys(self):
        json_str = json.dumps(self.answersys,indent=4)
        with open(self.filename4,'w') as file_object:
            file_object.write(json_str)

    def wrongans_update(self,listofwr: tuple):  # 更新错题集,默认为current_user,listofstring为3元组，(日期(一个str)，年级:str(1,2,3代表简单，中等，困难)，[错题的列表])
        # self.users_wrongans 是一个字典嵌套字典，其形式类似于{"zhouxinyi":{"2019.10.8":["2+3="],1:["1+1="]}}
        (date, pro_hard, Listofwrong) = listofwr
        if self.current_user not in self.users_wrongans.keys():
            self.users_wrongans[self.current_user] = {}
        if date not in self.users_wrongans[self.current_user].keys():
            self.users_wrongans[self.current_user][date] = Listofwrong[:]
        else:
            self.users_wrongans[self.current_user][date] += Listofwrong
        if pro_hard not in self.users_wrongans[self.current_user].keys():
            self.users_wrongans[self.current_user][pro_hard] = Listofwrong[:]
        else:
            self.users_wrongans[self.current_user][pro_hard] += Listofwrong
        if self.current_user not in self.users_wrongans_del.keys():
            self.users_wrongans_del[self.current_user] = Listofwrong[:]
        else:
            self.users_wrongans_del[self.current_user] += Listofwrong

    def wrongans_del(self, wrong_pro: str):  # 将用户错题集中的一道题目删除,如果该用户当前没有错题，则返回-1，否则返回1
        if self.current_user not in self.users_wrongans_del.keys():
            return -1
        else:
            self.users_wrongans_del[self.current_user].remove(wrong_pro)
            return 1

    def wrongans_achieve(self,key):  # 读取currrent user的错题集(无论是用难度读取或者用日期读取),若返回-1则代表当前登录用户还没有错题，否则返回错题List
        if self.current_user not in self.users_wrongans.keys():
            return []
        if key not in self.users_wrongans[self.current_user].keys():
            return []
        else:
            result = []
            for str11 in self.users_wrongans[self.current_user][key]:      #返回的list为tuple的list，每个tuple由(题目，答案)二元组组成
                str1 = str11[0:-1]
                cur = eval(str1.replace("x","*").replace("÷", "//"))
                result.append((str11,cur))
            return result

    def wrongans_achieve_both(self,date:str,grade:str):     #用于取出同时属于某个日期且某个年级的错题
        if date not in self.users_wrongans[self.current_user].keys():
            return None
        elif grade not in self.users_wrongans[self.current_user].keys():
            return None
        result = []
        re1 = self.users_wrongans[self.current_user][date]
        re2 = self.users_wrongans[self.current_user][grade]
        for re in re1:
            if re in re2:
                cur = eval(re[0:-1].replace("x","*").replace("÷", "//"))
                result.append((re,cur))
        return result


    def findpass(self,username:str,answer:str):   #通过我们设置的题目的答案来得到他的原始密码，注意此时用户尚未登陆
        if username not in self.answersys.keys():
            return False
        (password,ans) = self.answersys[username]
        if answer == ans:
            return password
        else:
            return None

    def deleteallusers(self): #销毁所有用户信息
        self.users = {}
        self.users_wrongans = {}
        self.users_wrongans_del = {}
        self.answersys = {}
        self.writefile_user()
        self.writefile_wrongans()
        self.writefile_wrongans1()
        self.writefile_anssys()